<?php
/**
 * Created by PhpStorm.
 * User: 程阳
 * Date: 2018/4/1
 * Time: 11:44
 */

namespace app\api\service;


use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;
use think\Exception;
use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;

class Pay
{
    private $orderNo;
    private $orderID;
    
    function __construct($orderID) {
        if(!$orderID){
            throw new Exception('订单号不允许为NULL');
        }
        $this->orderID = $orderID;
    }
    
    /**
     * 调用支付接口生成预订单，默认返回成功
     * @return array|bool
     */
    public function pay(){
        $this->checkOrderValid();
        $order = new OrderService();
        $status = $order->checkOrderStock($this->orderID);
        if(!$status['pass']){
            return $status;
        }else{
            // 调用微信支付，生成预订单，这里省略这一步
            return true;
        }
    }
    
    /**
     * 检查订单是否存在，生成订单的人和支付订单的人是否是同一个人，且判断订单是否被支付过
     * @return bool
     * @throws OrderException
     * @throws TokenException
     */
    private function checkOrderValid(){
        $order = OrderModel::where('id','=',$this->orderID)->find();
        if(!$order){
            throw new OrderException();
        }
        if(!Token::isValidOperate($order->user_id)){
            throw new TokenException([
                'msg' => '订单与用户不匹配',
                'errorCode' => 10003
            ]);
        }
        if($order->status != OrderStatusEnum::UNPAID){
            throw new OrderException([
                'code' => 400,
                'msg' => '订单已经支付过了',
                'errorCode' => 80003
            ]);
        }
        $this->orderNo = $order->order_no;
        return true;
    }
}